/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.barn.modular.barn.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.barn.modular.barn.entity.BarnView;
import vip.xiaonuo.barn.modular.barn.entity.BizBarn;
import vip.xiaonuo.barn.modular.barn.mapper.BarnViewMapper;
import vip.xiaonuo.barn.modular.barn.mapper.BizBarnMapper;
import vip.xiaonuo.barn.modular.barn.param.BizBarnAddParam;
import vip.xiaonuo.barn.modular.barn.param.BizBarnEditParam;
import vip.xiaonuo.barn.modular.barn.param.BizBarnIdParam;
import vip.xiaonuo.barn.modular.barn.param.BizBarnPageParam;
import vip.xiaonuo.barn.modular.barn.service.BizBarnService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.henhouse.modular.henhouse.mapper.BizHenhouseMapper;

import javax.annotation.Resource;
import java.util.List;

/**
 * 栏舍管理Service接口实现类
 *
 * @author zyb
 * @date  2023/11/17 14:31
 **/
@Service
@Slf4j
public class BizBarnServiceImpl extends ServiceImpl<BizBarnMapper, BizBarn> implements BizBarnService {

    @Resource
    private BizHenhouseMapper bizHenhouseMapper;

    @Resource
    private BizBarnMapper barnMapper;

    @Resource
    private BarnViewMapper barnViewMapper;

    @Override
    public Page<BarnView> page(BizBarnPageParam bizBarnPageParam) {
        QueryWrapper<BarnView> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizBarnPageParam.getHenhouseName())) {
            queryWrapper.lambda().eq(BarnView::getHenhouseId, bizBarnPageParam.getHenhouseName());
        }
        if(ObjectUtil.isNotEmpty(bizBarnPageParam.getName())) {
            queryWrapper.lambda().like(BarnView::getName, bizBarnPageParam.getName());
        }
        if(ObjectUtil.isNotEmpty(bizBarnPageParam.getState())){
            queryWrapper.lambda().like(BarnView::getState, bizBarnPageParam.getState());
        }
        if(ObjectUtil.isAllNotEmpty(bizBarnPageParam.getSortField(), bizBarnPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizBarnPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizBarnPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizBarnPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BarnView::getSortCode);
        }
        return barnViewMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizBarnAddParam bizBarnAddParam) {
        BizBarn bizBarn = BeanUtil.toBean(bizBarnAddParam, BizBarn.class);
        bizBarn.setSortCode(99);
        this.save(bizBarn);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult<String> edit(BizBarnEditParam bizBarnEditParam) {
        // 检测栏舍的父鸡舍下是否有同名的栏舍
        // 通过查找是否有同名的同父鸡舍id来实现
        QueryWrapper<BizBarn> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BizBarn::getHenhouseId, bizBarnEditParam.getHenhouseId());
        queryWrapper.lambda().eq(BizBarn::getName,bizBarnEditParam.getName());
        queryWrapper.lambda().eq(BizBarn::getCapacity,bizBarnEditParam.getCapacity());
        List<BizBarn> bizBarns = barnMapper.selectList(queryWrapper);
        if (!ObjectUtil.isEmpty(bizBarns)){
            return CommonResult.error("在该鸡舍下已经存在同名栏舍！");
        }

        // 执行修改
        BizBarn bizBarn = this.queryEntity(bizBarnEditParam.getId());
        BeanUtil.copyProperties(bizBarnEditParam, bizBarn);
        this.updateById(bizBarn);
        return CommonResult.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizBarnIdParam> bizBarnIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizBarnIdParamList, BizBarnIdParam::getId));
    }

    @Override
    public BizBarn detail(BizBarnIdParam bizBarnIdParam) {
        return this.queryEntity(bizBarnIdParam.getId());
    }

    @Override
    public BizBarn queryEntity(String id) {
        BizBarn bizBarn = this.getById(id);
        if(ObjectUtil.isEmpty(bizBarn)) {
            throw new CommonException("栏舍不存在，id值为：{}", id);
        }
        return bizBarn;
    }

    @Override
    public List<BizBarn> getListByHenhouseId(Integer id) {
        log.info("根据鸡舍id获取栏舍列表,id:{}",id);
        if (id == null || id == -1){
            throw new CommonException("鸡舍id不存在,id值为：{}",id);
        }
        LambdaQueryWrapper<BizBarn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizBarn::getHenhouseId, id);
        return this.list(queryWrapper);
    }
}
